package com.dxb.test.thread;

import java.util.concurrent.Semaphore;

/**
 * ClassName：com.dxb.test.thread.SemaphoreABC <br>
 * Description：Semaphore <br>
 *
 * @author 戴晓波 <br>
 * Date 2022/2/14/014 13:55 <br>
 * @version v1.0 <br>
 */
public class SemaphoreABC {

    static void print(Semaphore current, Semaphore next) {
        for (int i = 0; i < 10; i++) {
            try {
                //state-1<0就会锁住
                current.acquire();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName());
            //state+1，唤醒current.acquire()被锁住线程
            next.release();
        }
    }

    public static void main(String[] args) {
        Semaphore semaphoreA = new Semaphore(1);
        Semaphore semaphoreB = new Semaphore(0);
        Semaphore semaphoreC = new Semaphore(0);
        new Thread(() -> print(semaphoreA, semaphoreB), "A").start();
        new Thread(() -> print(semaphoreB, semaphoreC), "B").start();
        new Thread(() -> print(semaphoreC, semaphoreA), "C").start();
    }
}
